//
//  BlipErrors.m
//  blipTest
//
//  Created by dawid on 08-12-16.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "BlipErrors.h"
#import "AppController.h"
#import "RegexKitLite.h"

@implementation BlipErrors
+(BOOL)findError:(NSData*)receivedData
{
	NSString *dataString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
	NSString *regex = @"^ *\\d{3}";
	NSString *htmlError = @"^<html.*h1>(.*?)</";
	NSString *emptyError = @"^ *\\[\\]$";
	if ([dataString isMatchedByRegex:regex] == YES) {
#ifdef __DEBUG__

		NSLog(@"HTTP error message:%@", dataString);

#endif
		[dataString release];
		dataString = nil;
		
		return YES;
	} else if ([dataString isMatchedByRegex:@"^.{1,3}error.*$"] == YES){
		if ([dataString isMatchedByRegex:@"^.{1,3}error.*unauthorized.*$"] == YES){
#ifdef __DEBUG__

			NSLog(@"error:Blad autoryzacji");

#endif
			
		
		}else {
			
#ifdef __DEBUG__

			NSLog(@"error : %@", dataString);

#endif			
		}
#ifdef __DEBUG__

		//NSLog(@"error na zyczenie = %@", dataString);

#endif
		
		[dataString release];
		dataString = nil;

		return YES;
		
	}else if([dataString isMatchedByRegex:htmlError] == YES){
#ifdef __DEBUG__

		NSLog(@"error: %@", [dataString stringByMatching:htmlError withReferenceString:@"$1"]);

#endif

		return YES;
	}else if([dataString isMatchedByRegex:emptyError] == YES){
		return NO;
	}else {
		[dataString release];
		dataString = nil;
		return NO;
	}
	
}
+(NSString*)checkDownloadData:(NSData*)data
{
	NSString* dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];	
	[dataString autorelease];
	
	if ([BlipErrors findError:data] == YES){
		data = nil;
		return nil;
	}
	
	return 	dataString;
}

@end
